package com.example.test_witns;

import static org.junit.Assert.assertEquals;

import android.content.Context;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
        assertEquals("com.example.test_witns", appContext.getPackageName());
    }

    public static void main(String[] args) {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
        };

        try {
            // 创建 SSL 上下文
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);

            // 获取 SSL 套接字工厂
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 创建 SSL 套接字
            SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("104.43.113.253", 12345);

            // 开始 SSL 握手
            sslSocket.startHandshake();

            // 发送消息到服务端
            PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
            out.println("你好，服务端！");

            // 接收服务端的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
            String response = in.readLine();
            System.out.println("服务端响应：" + response);

            // 关闭连接
            in.close();
            out.close();
            sslSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}